﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Timers;
using WindowsStateService.Data;

namespace WindowsStateService.Manager
{
    public class CacheManager
    {
        private CacheRule _mode;
        private string _folder;
        private long _max_size;
        private long _current_size;
        private string _datas_root_folder;
        private string _logs_folder;
        private Timer _timer;
        public CacheManager(long max_size = 1073741824)
        {
           // _mode = mode;
           // _folder = Path.Combine(folder, CommonPath.GetAssemblyVersion());
            _max_size = max_size;  
        }

        public void Start()
        {
            //DirectoryInfo dir_info = new DirectoryInfo(_folder);
            //if(!dir_info.Exists)
            //{
            //    ServiceLogManager.Instance.Error($"文件夹：{_folder}路径不存在。");
            //    return;
            //}
            //_logs_folder = Path.Combine(dir_info.FullName,  "Logs");
            //_datas_root_folder = Path.Combine(dir_info.FullName, "Datas");
            StartTimer();
        }

        private void InitializeModeAndPath()
        {
            _mode = ConfigFileHelper.Instance.CacheType;
            _folder = Path.Combine(ConfigFileHelper.Instance.DataPath, CommonPath.GetAssemblyVersion());
            DirectoryInfo dir_info = new DirectoryInfo(_folder);
            if (!dir_info.Exists)
            {
                ServiceLogManager.Instance.Error($"文件夹：{_folder}路径不存在。");
                return;
            }
            _logs_folder = Path.Combine(dir_info.FullName, "Logs");
            _datas_root_folder = Path.Combine(dir_info.FullName, "Datas");
        }

        public void Stop()
        { 
            _timer.Stop();
        }

        private void StartTimer()
        {
            _timer = new Timer();
            _timer.Elapsed += OnTimerElapsed;
            _timer.Interval = 60 * 60 * 1000;
            _timer.Start();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                //Debugger.Launch();
                InitializeModeAndPath();
                RemoveTempDatas();
                if (RequireDoRemove())
                {
                    DoRemove();
                }
            }
            catch (Exception ex)
            {
                ServiceLogManager.Instance.Error(ex.StackTrace);
            }
        }

        private long GetDirectorySize()
        {
            long totalSize = 0;

            try
            {
                // 获取文件列表
                string[] files = Directory.GetFiles(_folder, "*.*", SearchOption.AllDirectories);

                // 计算总大小
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    totalSize += fileInfo.Length;
                }
            }
            catch (Exception ex)
            {
                ServiceLogManager.Instance.Error($"计算文件夹大小出错。{ex.StackTrace}");
            }

            return totalSize;
        }

        private void DoRemove()
        {
            string[] log_files = Directory.GetFiles(_logs_folder, "*.log");
            string[] datas_files = Directory.GetFiles(_datas_root_folder, "*.data", SearchOption.AllDirectories);
            if (_mode == CacheRule.ThirtyDays)
            {
                List<string> all_files = new List<string>(log_files);
                all_files.AddRange(datas_files);
                DateTime t_end = DateTime.Now.Date;
                DateTime t_start = t_end.AddDays(-30);
                foreach (string file in all_files)
                {
                    try
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        string file_name = fileInfo.Name.Split('.')[0];
                        DateTime.TryParse(file_name, out DateTime date);
                        if (date <= t_start)
                        {
                            File.Delete(file);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            if(_mode == CacheRule.OneG)
            {
                List<string> log_ls = log_files.ToList();
                List<string> datas_ls = datas_files.ToList();
                log_ls.Sort();
                datas_ls.Sort();
                string file_name = GetFileName(log_ls[0]);
                int index = 0;
                while (index < log_ls.Count)
                {
                   
                    try
                    {
                        string name = GetFileName(log_ls[index]);
                        if (file_name == name)
                        {
                            File.Delete(log_ls[index]);
                        }                      
                    }
                    catch
                    {
                        index++;
                        continue ;
                    }
                    index++;
                }

                file_name = GetFileName(datas_ls[0]);
                index = 0;
                while (index < datas_ls.Count)
                {
                    try
                    {
                        string name = GetFileName(datas_ls[index]);
                        if (file_name == name)
                        {
                            File.Delete(datas_ls[index]);
                        }
                    }
                    catch
                    {
                        index++;
                        continue;
                    }
                    index++;
                }
            }

        }

        private string GetFileName(string full_file_name)
        {
            string file_name = new FileInfo(full_file_name).Name;
            if (string.IsNullOrWhiteSpace(file_name))
                return string.Empty;
            string fname = file_name;
            string[] eles = fname.Split('.');
            if(eles.Length > 1)
            {
                return eles[0];
            }
            return fname;
        }


        /// <summary>
        /// 删除临时文件
        /// </summary>
        private void RemoveTempDatas()
        {
            string[] files = Directory.GetFiles(_folder, "*.temp", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                try
                {
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }
                catch
                {
                    continue;
                }
            }
        }

        private bool RequireDoRemove()
        {
            bool result = false;
            if(_mode == CacheRule.ThirtyDays)
            {
                DirectoryInfo info = new DirectoryInfo(_logs_folder);
                FileInfo[] files = info.GetFiles("*.log", SearchOption.TopDirectoryOnly);
                result = files.Length > 30;
            }
            else // OneG
            {
                result = GetDirectorySize() > _max_size;
            }
            return result;
        }
    }
}
